package com.wwz.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwz.constant.ProjectConst;
import com.wwz.entity.User;
import com.wwz.exception.EcoBootException;
import com.wwz.mapper.UserMapper;
import com.wwz.query.UserQuery;
import com.wwz.service.IUserService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {


    @Override
    public IPage<User> toPage(UserQuery query) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(query.getCompanyId())){
            wrapper.eq(User::getCompanyId,query.getCompanyId());
        }
        if (StrUtil.isNotEmpty(query.getDepartmentId())){
            wrapper.eq(User::getDepartmentId,query.getDepartmentId());
        }
        if (query.getHasDept()!=null){
            switch (query.getHasDept()){
                // 未分配部分
                case 0:wrapper.isNull(User::getDepartmentId);break;
                // 已分配
                case 1:wrapper.isNotNull(User::getDepartmentId);break;
                default: throw new EcoBootException("查询条件错误");
            }
        }
        wrapper.orderByDesc(User::getCreateTime);
        IPage<User> userIPage = this.page(query.toPage(), wrapper);
        List<User> records = userIPage.getRecords();
        for (User user : records) {
            if (ProjectConst.STATUS_NO.equals(user.getFormOfEmployment())){
                user.setFormOfEmploymentValue(ProjectConst.EMP_FORM_FORMAL);
            }
            if (ProjectConst.STATUS_OK.equals(user.getFormOfEmployment())){
                user.setFormOfEmploymentValue(ProjectConst.EMP_FORM_INFORMAL);
            }
        }
        return userIPage;
    }

    @Override
    public void addOrUpData(User user) {
        String companyId = "7ac32217-25bf-459a-b07d-b739c5c33210";
        if ( StrUtil.isEmpty(user.getUsername()) ){
            throw new EcoBootException("字段不能为空");
        }
        User one = getById(user.getId());
        // 添加
        if (one == null){
            user.setId(StrUtil.uuid());
            // 启用状态
            user.setCompanyId(companyId);
            user.setEnableState(ProjectConst.STATUS_NO);
            user.setCreateTime(new Date());
            save(user);
            return;
        }
        updateById(user);
    }

    @Override
    public void deleteById(String id) {
        User one = getOne(new LambdaQueryWrapper<User>()
                .eq(User::getId, id), false);
        if (one == null){
            throw new EcoBootException("此用户不存在");
        }
        removeById(id);
    }
}
